﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace clss4_work2
{
    public class Clock
    {
        private int currentTime;//当前时间
        private int bookTime;//设定时间
                       
        public void Tik() {
            if (currentTime <= bookTime)
                Console.WriteLine("滴答滴答");
        }                        //声明委托
        public delegate void AlarmEventHandler(Object sender, AlarmEventArgs e);
        public event AlarmEventHandler Alarmed;       //声明事件

        // 定义AlarmEventArgs类，传递给Observer所感兴趣的信息
        public class AlarmEventArgs : EventArgs
        {
            public readonly int currentTime;
            public readonly int bookTime;
            public AlarmEventArgs(int currentTime)
            {
                this.currentTime = currentTime;
            }
        }

        // 可以供继承自 Clock 的类重写，以便继承类拒绝其他对象对它的监视
        protected virtual void OnAlarm(AlarmEventArgs e)
        {
            if (Alarmed != null)
            {       // 如果有对象注册
                Alarmed(this, e);       // 调用所有注册对象的方法
            }
        }

        //显示
        public void AlarmDo()
        {
            for (int i = 0; i <= 100; i++)
            {
                currentTime = i;


                //建立AlarmEventArgs 对象。
                AlarmEventArgs e = new AlarmEventArgs(currentTime);
                OnAlarm(e);       // 调用方法

            }
        }
    }

    // 警报器
    public class Alarm
    {
        public void MakeAlert(Object sender, Clock.AlarmEventArgs e)
        {
            Clock heater = (Clock)sender;
            
            Console.WriteLine("Alarm: 嘤嘤嘤，已经过去 {0} 秒了：", e.currentTime);
            Console.WriteLine();
        }

    }

    // 显示器
    public class Display
    {
        public static void ShowMsg(Object sender, Clock.AlarmEventArgs e)
        {       //静态方法
            Clock clock = (Clock)sender;
            
            Console.WriteLine("Display： ，当前时间已过：{0}秒。还剩下{1}秒", e.currentTime, (e.bookTime - e.currentTime));
            Console.WriteLine();
        }
    }

    class Program
    {

        static void Main()
        {
            Clock clock = new Clock();
            Alarm alarm = new Alarm();
            clock.Tik();

            clock.Alarmed += alarm.MakeAlert;       //注册方法

            clock.Alarmed += Display.ShowMsg;              //注册静态方法

            clock.AlarmDo();       // ，会自动调用注册过对象的方法
        }
    }

}
